package com.zmx.common.common.web;

import com.zmx.common.common.dto.BaseDto;
import com.zmx.common.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Description: controller控制器的抽象基类
 * @ClassName: AbstractController
 * @Author zhaomxr
 * @Date 2021-09-29 09:13
 */
public class AbstractController<TDto extends BaseDto, TService extends BaseService> {

    @Autowired
    private TService service;

    @PostMapping
    @SuppressWarnings("unchecked")
    public TDto create(@RequestBody TDto dto) {
        return (TDto) service.create(dto);
    }

    @PutMapping
    @SuppressWarnings("unchecked")
    public TDto update(@RequestBody TDto dto) {
        return (TDto) service.update(dto);
    }

    @PostMapping("/delete")
    @SuppressWarnings("unchecked")
    public void delete(@RequestParam(required = true) Long[] ids) {
        service.deleteBatch(ids);
    }

    @GetMapping("findById/{id}")
    public TDto findById(@PathVariable(required = true) Long id) {
        return (TDto) service.entityToDto(service.findById(id));
    }

    @GetMapping("findByIdIn")
    public List<TDto> findByIdIn(@RequestParam(required = true) Long[] ids) {
        return (List<TDto>) service.findByIdIn(ids);
    }

    @PostMapping("getAll")
    @SuppressWarnings("unchecked")
    public Page<TDto> getAll(@RequestBody Map<String,Object> searchParams, int currentPage, int pageSize){
        //默认按照创建时间逆序排列
        searchParams.put("createTime","desc");
        return service.getAll(searchParams, currentPage, pageSize, true);
    }
}
